package com.loong.common.wechat.auth;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.ParserConfig;
import com.loong.common.http.OKHttpUtil;
import com.loong.common.wechat.constant.API;
import com.loong.common.wechat.model.result.*;
import jodd.util.Base64;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import com.loong.common.wechat.model.result.AccessTokenResult;
import com.loong.common.wechat.model.result.UserInfoResult;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.AlgorithmParameters;
import java.security.Security;
import java.util.Arrays;

@Component
public class AuthUtils {

    @Resource
    private OKHttpUtil okHttpUtil;

    @Resource
    private ParserConfig parserConfig;

    public AccessTokenResult accessToken(String appId,String secret,String code){
        String url = API.AUTH.ACCESS_TOKEN;
        String param = "?appid="+appId+"&secret="+secret+"&code="+code+"&grant_type=authorization_code";
        String result = okHttpUtil.get(url + param);
        AccessTokenResult accessTokenResult = JSONObject.parseObject(result,AccessTokenResult.class,parserConfig);
        return accessTokenResult;
    }

    /**
     * 获取微信授权用户信息
     * @param accessToken
     * @param openId
     * @return
     */
    public UserInfoWeChatResult getUserInfo(String accessToken, String openId){
        String url = API.AUTH.USER_INFO;
        String param ="?access_token="+accessToken+"&openid="+openId+"&lang=zh_CN";
        String result = okHttpUtil.get(url + param);
        UserInfoWeChatResult userInfo = JSONObject.parseObject(result, UserInfoWeChatResult.class,parserConfig);
        return userInfo;

    }





    /**
     *
     * 小程序 根据code获取session_key，openid
     * @param appId
     * @param secret
     * @param code
     * @return
     * openid,session_key
     * 可以通过 jsonObject.get(session_key)
     */
    public SessionKeyOrOpenIdResult getSessionKeyOrOpenId(String appId, String secret, String code){
        String url = API.AUTH.JSCODE2SESSION;
        String param = "?appid="+appId+"&secret="+secret+"&js_code="+code+"&grant_type=authorization_code";
        String result = okHttpUtil.get(url + param);
        SessionKeyOrOpenIdResult sessionKeyOrOpenIdResult = JSONObject.parseObject(result,SessionKeyOrOpenIdResult.class,parserConfig);
        return sessionKeyOrOpenIdResult;
    }

    /**
     * 小程序 获取用户加密信息
     * @param encryptedData
     * @param sessionKey
     * @param iv
     * @return
     */
    public  UserEncryptedDataResult getUserInfo(String encryptedData, String sessionKey, String iv){
        // 被加密的数据
        byte[] dataByte = Base64.decode(encryptedData);
        // 加密秘钥
        byte[] keyByte = Base64.decode(sessionKey);
        // 偏移量
        byte[] ivByte = Base64.decode(iv);
        try {
            // 如果密钥不足16位，那么就补足.  这个if 中的内容很重要
            int base = 16;
            if (keyByte.length % base != 0) {
                int groups = keyByte.length / base + (keyByte.length % base != 0 ? 1 : 0);
                byte[] temp = new byte[groups * base];
                Arrays.fill(temp, (byte) 0);
                System.arraycopy(keyByte, 0, temp, 0, keyByte.length);
                keyByte = temp;
            }
            // 初始化
            Security.addProvider(new BouncyCastleProvider());
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding","BC");
            SecretKeySpec spec = new SecretKeySpec(keyByte, "AES");
            AlgorithmParameters parameters = AlgorithmParameters.getInstance("AES");
            parameters.init(new IvParameterSpec(ivByte));
            cipher.init( Cipher.DECRYPT_MODE, spec, parameters);// 初始化
            byte[] resultByte = cipher.doFinal(dataByte);
            if (null != resultByte && resultByte.length > 0) {
                String result = new String(resultByte, "UTF-8");
                UserEncryptedDataResult userEncryptedDataResult = JSONObject.parseObject(result, UserEncryptedDataResult.class,parserConfig);
                return userEncryptedDataResult;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取用户简单信息 不包含openid
     * @param rawData
     * @return
     */
    public UserRawDataResult getUserInfo(String rawData){
        if(ObjectUtils.isEmpty(rawData)) return null;


        UserRawDataResult userInfo = JSONObject.parseObject(rawData, UserRawDataResult.class, parserConfig);
        return userInfo;
    }



}
